<?php
/*****************************************************************
	Std PHP Framework
	Module CLI 
	$Id: mod_cli.php 4 2008-02-25 23:18:23Z RusAnon $
*****************************************************************/
/*****************************************************************
	Module CLI Configuration
*****************************************************************/
/*
$argl = array(
	"argname" => array(
		"required"	=> 1,
		"hasvalue"	=> 1,
		"default"	=> "default",
		"desc"		=> "description",
	),
	"help" => array(
		"required"	=> 0,
		"hasvalue"	=> 0,
		"desc"		=> "This help page.",
	),	
);
*/
$argl = array_merge($argl,array(
	"help" => array(
		"required"	=> 0,
		"hasvalue"	=> 0,
		"desc"		=> "This help page.",
	),
));
if(!defined("STDIN"))
{
	define("STDIN", fopen('php://stdin','r'));
}
function ProcessArgs($argl)
{
	global $args,$argv;
	foreach ($argl as $arg => $p)
	{
		if (isset($p['default']))
		{
			$args[$arg]=$p['default'];
		}
	}
	foreach ($argv as $i => $arg)
	{
		if (preg_match("~^--([\w\d\_\-]+)(=(.+))?$~",$arg,$m))
		{
			if (isset($argl[$m[1]]))
			{
				if ($argl[$m[1]]['hasvalue'])
					$args[$m[1]]=$m[3];
				else
					$args[$m[1]]=1;
			}
		}
	}
	$fail = 0;
	foreach ($argl as $arg => $p)
	{
		if ($p['required'] AND !isset($args[$arg]))
			$fail = 1;	
	}
	if ($fail)
	{
		echo "Some required parameters are missing !\r\n";
		PrintHelp($argl);
	}
}
function PrintHelp($argl)
{
	echo "Params supported : \r\n";
	foreach ($argl as $arg => $p)
	{
		echo "  --{$arg}";
		if ($p['hasvalue'])
			echo "=value";
		echo "\t";
		if (strlen($arg) < 6)
			echo "\t";
		if ($p['required'])
			echo "* ";
		else
			echo "  ";
		echo "$p[desc]\t";
		if ($p['default'])
			echo "Default : '$p[default]'\t";		
		echo "\r\n";
	}
	die ("Params marked with * are obligatory unless have default values.");
}
function EchoMsg($txt)
{
	global $procId;
	echo $procId." ".date("Y-m-d H:i:s")."\t$txt\r\n";
}
function EchoMsgDebug($msg,$debug=1)
{
	global $args;
	if ($args['debug'] >= $debug)
	{
		EchoMsg($msg);
	}
}
function GetProcId($ThreadID='',$ThreadName='')
{
	if ($ThreadID)
		return getmypid()." #{$ThreadID} $ThreadName";
	else
		return getmypid();
}
function CLIReadLn()
{
	$r = fread(STDIN,1024);
	return $r;
}
?>